package ferp.center.server.task;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.taskqueue.TaskHandle;
import ferp.center.server.Action;
import ferp.center.server.entity.Range;
import ferp.center.server.ranking.Lookup;
import ferp.center.server.ranking.Ranker;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;

/**
 * User: igorgok
 * Date: 6/6/13 12:24 PM
 */
public class TaskRangeTreeRemoveLeaf extends HttpServlet
{
  public static void queue(Range leaf)
  {
    TaskHandle t = Ranker.queue(withUrl(URL).param(RID, String.valueOf(KeyFactory.keyToString(leaf.getKey()))));

    System.out.println("queued leaf removal, key=[" + leaf.getKey() + "]");
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    Action.execute(request, new Action.Task()
    {
      @Override
      protected void run(EntityManager em, HttpServletRequest request) throws IOException
      {
        String rid = request.getParameter(RID);
        Range leaf = em.find(Range.class, KeyFactory.stringToKey(rid));

        if (leaf != null)
        {
          // we need to confirm that there are no ratings for this leaf
          if (Lookup.ratings(em, leaf).size() == 0)
          {
            // reset the reference counter to ensure removal
            leaf.setSize(0);
            // remove the leaf
            Ranker.remove(em, leaf);
          }
        }
        else
          log("could not find range " + rid);
      }
    });
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    throw new ServletException("GET method is not supported");
  }

  private static final String URL = Url.rt("remove/leaf");
  private static final String RID = "rid";
}
